package com.haochang.chunkvod.controller.fragment.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseListView;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.config.ServerErrorCodeConfig;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.adapter.order.OrderQueryTakeOutAdapter;
import com.haochang.chunkvod.model.custom.CustomDialogData;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.query.OrderInfo;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * 点餐--外带
 *     @author Yangjie
 *     className TakeOutHistoryFragment
 *     created at  2016/10/25  20:35
 */

public class TakeOutHistoryFragment extends BaseFragment
{
	private TitleView titleView;
	private OrderQueryTakeOutAdapter adapter;
	private String billId;
	private OrderData orderData;
	private CustomDialogData customDialogData;
	private List<OrderInfo> infoList = new ArrayList<OrderInfo>();
	private GoodsInfo resultInfo;
	private String flow_code;
	private String content;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.fragment_order_take_out_history, container, false);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	private void initData()
	{
		orderData = new OrderData((BaseActivity) getActivity());
		customDialogData = new CustomDialogData((BaseActivity) getActivity());
		requestData();
	}

	private void initView()
	{
		String roomNum = getArguments().getString(IntentKey.ROOM_NUM);
		String roomId = getArguments().getString(IntentKey.ROOM_ID);
		billId = getArguments().getString(IntentKey.BILL_ID);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(roomNum).setBackText("主页").setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				getActivity().finish();
			}

			@Override
			public void onDoneClick()
			{
				{
					List<String> list = new ArrayList<String>();
					list.add("退出登录");
					int location[] = new int[2];
					ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
					img.getLocationOnScreen(location);
					int x = location[0];
					final VodPopWindow pop = new VodPopWindow(getActivity(), list);
					pop.showPopupWindow(titleView, x);
					pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
					{
						@Override
						public void onSelectItem(int position)
						{
							switch (position)
							{
							case 0:
								((BaseActivity) getActivity()).loginOut();
								break;
							default:
								break;
							}
						}
					});
				}
			}
		});
		BaseListView listView = (BaseListView) findViewById(R.id.listView);
		adapter = new OrderQueryTakeOutAdapter(this, getActivity());
		listView.setAdapter(adapter);
	}

	/**
	 * 请求数据
	 */
	private void requestData()
	{
		orderData.requestOrderTakeOutSearch(billId, new OrderData.IOrderSearchListener()
		{
			@Override
			public void onRequestSuccess(List<OrderInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					infoList.clear();
					infoList.addAll(list);
					adapter.setData(infoList);
				} else
				{
					infoList.clear();
					adapter.setData(infoList);
					ToastUtils.showText(getContext(), "暂无记录");
				}
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IntentCode.ORDER_SEARCH_REQUEST_GIVE && resultCode == Activity.RESULT_OK)
		{
			String token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			final GoodsInfo info = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("order_id", info.getD_id_value());
			String type;
			if (info.getGoods_type() == VodConstant.ACTIVE_TYPE)
				type = "-1";
			else if (info.getGoods_type() == VodConstant.BUNDLE_TYPE)
				type = "1";
			else
				type = "0";
			map.put("order_type", type);
			map.put("auth_token", token);
			customDialogData.requestCancelGive(true, map, new CustomDialogData.ICancelGiveListener()
			{
				@Override
				public void onRequestSuccess(JSONObject jsonObject)
				{
					ToastUtils.showText(getActivity(), "取消赠送成功");
					requestData();
				}

				@Override
				public void onFail(int errno, String errMsg)
				{
					ToastUtils.showText(getActivity(), errMsg);
				}
			});
		} else if (data != null && requestCode == IntentCode.ORDER_SEARCH_REQUEST_BACK && resultCode == Activity.RESULT_OK)
		{
			resultInfo = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
			flow_code = data.getStringExtra(IntentKey.FLOW_CODE);
			content = data.getStringExtra(IntentKey.BACK_NUMBER);
			//boolean need_permission = data.getBooleanExtra(IntentKey.NEED_PERMISSION, false);
			if (null != resultInfo)
			{
				requestCurrentStaffPermission();
			}
		} else if (data != null && requestCode == IntentCode.ORDER_SEARCH_REQUEST_BACK_PERMISSION && resultCode == Activity.RESULT_OK)
		{
			String token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			requestBack(resultInfo, content, flow_code, token);
		} else if (requestCode == IntentCode.ORDER_SEARCH_REQUEST_CHANGE && resultCode == Activity.RESULT_OK)
		{
			//更换商品成功，重新请求数据
			requestData();
		}
	}

	/**
	 * 当前账号退单权限验证,不弹权限验证框，直接请求接口验证
	 */
	private void requestCurrentStaffPermission()
	{
		final String eventName;
		if (resultInfo.getGoods_type() == VodConstant.ACTIVE_TYPE)
			eventName = "门店POS系统>点餐系统模块>外带已点>退单(包段活动)";//传入权限验证事件名(活动)
		else
			eventName = "门店POS系统>点餐系统模块>外带已点>退单";//传入权限验证事件名(单品)
		new HostessData((BaseActivity) getActivity()).requestAuthorization(ApiConfig.VOD_TOKEN, "", "", eventName, new HostessData.ResultResponseString()
		{
			@Override
			public void onRequestSuccess(String token)
			{
				//当前账号权限验证成功直接退单
				if (!TextUtils.isEmpty(token))
				{
					requestBack(resultInfo, content, flow_code, token);
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				//当前账号权限验证失败弹出权限验证框
				ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "权限验证失败" : errMsg);
				if (errno == ServerErrorCodeConfig.CURRENT_STAFF_BACK)
				{
					Intent intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
					intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.VOD_TOKEN);//传入接口名字
					intent.putExtra(IntentKey.TOKEN_EVENT, eventName);//传入接口名字
					startActivityForResult(intent, IntentCode.ORDER_SEARCH_REQUEST_BACK_PERMISSION);
				}
			}
		});
	}

	/**
	 * 请求退单
	 * @param info info
	 * @param quantity quantity
	 * @param flow_code 账单流水号
	 * @param token 退单时的权限token/外带暂时没有用上
	 */
	private void requestBack(final GoodsInfo info, String quantity, final String flow_code, String token)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("outer_id", info.getD_id_value());
		map.put("goods_id", info.getGoodsId());
		map.put("quantity", quantity);
		map.put("auth_token", token);
		info.setBackNum(Integer.parseInt(content));
		customDialogData.requestBack(true, map, new CustomDialogData.IGoodsBackListener()
		{
			@Override
			public void onRequestSuccess(JSONObject jsonObject)
			{
				ToastUtils.showText(getActivity(), "退单成功");
				requestData();
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				ToastUtils.showText(getActivity(), errMsg);
			}
		});
	}

}
